package db

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"strconv"
	"take-a-break/component/log"
	"take-a-break/component/mysql"
	"xorm.io/xorm"
)

func GetMasterDb() *xorm.Engine {
	return mysql.GetSession("default").Master()
}

func GetSlaveDb() *xorm.Engine {
	return mysql.GetSession("default").Slave()
}

func GetMasterDbSession(ctx context.Context) *xorm.Session {
	if ctx == nil {
		ctx = context.Background()
	}
	return GetMasterDb().NewSession().Context(ctx)
}

func GetSlaveDbSession(ctx context.Context) *xorm.Session {
	if ctx == nil {
		ctx = context.Background()
	}
	return GetSlaveDb().NewSession().Context(ctx)
}

type CallBack func(session *xorm.Session) error

func Transaction(ctx context.Context, callBack CallBack) error {
	session := GetMasterDbSession(ctx)
	defer func(session *xorm.Session) {
		if err := session.Close(); err != nil {
			ck_log.LogCtx(ctx).Errorw("session关闭失败:", zap.Error(err))
		}
	}(session)
	if err := session.Begin(); err != nil {
		if rollbackErr := session.Rollback(); rollbackErr != nil {
			return errors.New("服务异常, 稍后重试")
		}
		return errors.New("服务异常, 稍后重试")
	}
	if err := callBack(session); err != nil {
		if rollbackErr := session.Rollback(); rollbackErr != nil {
			return errors.New("服务异常, 稍后重试")
		}
		return err
	}
	if err := session.Commit(); err != nil {
		return errors.New("服务异常, 稍后重试")
	}
	return nil
}

func GetInSqlInt(col string, in []int) string {
	sql := col + " in ("
	len := len(in) - 1
	for k, v := range in {
		sql += strconv.Itoa(v)
		if k != len {
			sql += ","
		}
	}
	sql += ")"
	return sql
}

func GetInSqlString(col string, in []string) string {
	sql := col + " in ("
	len := len(in) - 1
	for k, v := range in {
		sql += "'" + v + "'"
		if k != len {
			sql += ","
		}
	}
	sql += ")"
	return sql
}

//设置页面
func BuildPage(dbSession *xorm.Session, page, size int) {
	dbSession.Limit(size, (page-1)*size)
}
